package deepr.src;

import deepr.anno.SchemaType;
import deepr.behaviour.RequestDispose;
import deepr.core.SchemaData;
import deepr.core.SchemaManager;
import deepr.entity.DeeprRequest;
import deepr.entity.DeeprResponse;
import deepr.src.graph.GraphDispose;
import deepr.src.pg.PgDispose;

public class DeeprParse {

  public static DeeprResponse run(DeeprRequest deeprRequest, Integer method) throws Exception {
    String object = deeprRequest.getObject();
    SchemaData schemaData = SchemaManager.getSchemaData(object);
    SchemaType schemaType = schemaData.getSchemaType();
    RequestDispose dispose;

    switch (schemaType) {
      case PG:
        dispose = new PgDispose();
        break;
      case NEO4J:
        dispose = new GraphDispose();
        break;
      default:
        throw new IllegalStateException("Unexpected schemaType: " + schemaType);
    }
    Class<?> handler = schemaData.getHandler();
    if (handler != null) {
      handler.getMethod("beforeQuery",
          RequestDispose.class, DeeprRequest.class).
          invoke(handler.newInstance(), dispose, deeprRequest);
    }
    if (dispose.getDeeprResponse() == null) {
      if (method == 1) {
        dispose.list(deeprRequest);
      } else
        dispose.info(deeprRequest);
    }
    if (handler != null)
      handler.getMethod("afterQuery",
          RequestDispose.class, DeeprRequest.class).
          invoke(handler.newInstance(), dispose, deeprRequest);
    return dispose.getDeeprResponse();
  }


}
